//
//  HomeViewController.m
//  SP2P
//
//  Created by 吴建东 on 16/6/1.
//  Copyright © 2016年 EIMS. All rights reserved.
//

#import "HomeViewController.h"
#import "AdScrollView.h"
#import "CacheUtil.h"
#import "AdWebViewController.h"
#import "SQBDetailViewController.h"
#import "TransferredViewController.h"
#import "AddBankCardViewController.h"
#import "DWRollScrollView.h"
#import "PublicNoticeView.h"
#import "NewExperienceView.h"
#import "MessageDetailViewController.h"
@interface HomeViewController ()<HTTPClientDelegate,FocusImageFrameDelegate,UIAlertViewDelegate,DWRollScrollViewDelegate>
{
    UILabel *_titleLabel;
    UIImageView *_stausImageView;
    UILabel *_rateValue;
    UILabel *_rateLabel;
    ClickButton *_tenderButton;
    
    NSInteger       _typeNum;

    
}
@property (nonatomic, strong) UIScrollView   *scrollContent;
@property (nonatomic, strong) PublicNoticeView *publicView;
@property (nonatomic, strong) DWRollScrollView   *adScrollView;// 广告轮播图
@property (nonatomic, strong) NSMutableArray *adArrays;
@property (nonatomic, strong) NSMutableArray *tempArrays;

@property (nonatomic, strong) UIScrollView   *tenderInfoScrollView;

@property (nonatomic, strong) NetWorkClient  *requestClient;
@property (nonatomic, copy  ) NSString       *cacheFileName;

@end

@implementation HomeViewController
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self.tabBarController.tabBar setHidden:NO];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self initNavigationBar];
    if(iOS7){
     self.edgesForExtendedLayout = UIRectEdgeNone;
    }
    // 初始化数据
    [self initData];
    // 读取图片数据
    [self readData];
    // 初始化视图
    [self initView];
    NSLog(@"1111111");
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(gotoShareTab) name:@"gotoShareTab" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(gotoMessage:) name:@"gotoMessage" object:nil];
}

- (void)gotoShareTab {
    [self.tabBarController setSelectedIndex:2];
}

#pragma mark - Action
- (void)tenderButtonClick {
    SQBDetailViewController *detail = [[SQBDetailViewController alloc] init];
    detail.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detail animated:YES];
    
    return;
    if (AppDelegateInstance.userInfo == nil) {
        [ReLogin goLogin:self];
        return;
    }
//    [ReLogin testRealNameVerifyStaus:self];
    
    if (AppDelegateInstance.userInfo.realName.length<=0 || !AppDelegateInstance.userInfo.hasBindCard) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"您尚未进行实名认证" message:@"是否前去实名认证？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        alert.tag = 7;
        [alert show];
        return;
    }
    
    TransferredViewController *transfer = [[TransferredViewController alloc] initWithNibName:@"TransferredViewController" bundle:nil];
    transfer.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:transfer animated:YES];
}

- (void)tenderInfoViewTap {
    SQBDetailViewController *detail = [[SQBDetailViewController alloc] init];
    detail.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detail animated:YES];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag==7 && buttonIndex==1) {
        //去实名认证
        AddBankCardViewController *addBankCard = [[AddBankCardViewController alloc] init];
        addBankCard.editType = 1;
        addBankCard.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:addBankCard animated:YES];
    }else if (alertView.tag==10000 && buttonIndex==0) {
        
        if ([Baseurl isEqualToString:@"http://www.suicunsuiqu.com"]) {
            [[UIApplication sharedApplication]openURL:[NSURL URLWithString:AppDownloadURL]];
        }
    }
}

#pragma mark - FocusImageFrameDelegate
- (void)foucusImageFrame:(AdScrollView *)imageFrame didSelectItem:(AdvertiseGallery *)item {
    DLOG(@"广告栏选中%ld",(long)item.tag);
    if(item.urlStr.length > 0)
    {
        AdWebViewController *adWebView = [[AdWebViewController alloc] init];
        adWebView.urlStr = item.urlStr;
        adWebView.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:adWebView animated:YES];
    }
}

#pragma mark - DWRollScrollViewDelegate
- (void)scrollViewDidSelectAtIndex:(NSInteger)selectIndex {
    AdvertiseGallery *model = _adArrays[selectIndex];
    
    if(model.urlStr.length > 0) {
        AdWebViewController *adWebView = [[AdWebViewController alloc] init];
        adWebView.urlStr = model.urlStr;
        adWebView.hidesBottomBarWhenPushed = YES;
        [self.navigationController pushViewController:adWebView animated:YES];
    }
}

#pragma mark - Data
- (void)initData {
    _adArrays = [[NSMutableArray alloc]init];
    _tempArrays = [[NSMutableArray alloc]init];
}

// 请求数据
- (void)requestData {
    _typeNum = 1;
    
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    // app首页（opt=122）
    [parameters setObject:@"122" forKey:@"OPT"];
    [parameters setObject:@"" forKey:@"body"];
    [parameters setObject:@"" forKey:@"id"]; //栏目id
    
    _cacheFileName = [CacheUtil creatCacheFileName:parameters];
    
    if (_requestClient == nil) {
        _requestClient = [[NetWorkClient alloc] init];
        _requestClient.delegate = self;
    }
    [_requestClient requestGet:@"app/services" withParameters:parameters];
}

bool isUpdate = YES;
// 版本更新
- (void)upload {
    if (isUpdate) {
        isUpdate = NO;
        DLOG(@"版本更新");
        _typeNum = 2;
        NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
        [parameters setObject:@"127" forKey:@"OPT"];
        [parameters setObject:@"" forKey:@"body"];
        [parameters setObject:@"2" forKey:@"deviceType"];
        
        if (_requestClient == nil) {
            _requestClient = [[NetWorkClient alloc] init];
            _requestClient.delegate = self;
        }
        [_requestClient requestGet:@"app/services" withParameters:parameters];
        
    }else return;
}



//网络数据回调代理
- (void)startRequest {
    
}

// 返回成功
- (void)httpResponseSuccess:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didSuccessWithObject:(id)obj {
   
    
    if (_typeNum == 1) {
        [self processData:obj isCache:NO];// 读取当前请求到的数据
    }else {
        // 获取服务器版本
        NSString *version = [obj objectForKey:@"version"];
        if (codeNum < [[obj objectForKey:@"code"] integerValue]) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"版本更新" message:[NSString stringWithFormat:@"有最新的版本%@，是否前往更新？", version] delegate:self cancelButtonTitle:@"马上更新" otherButtonTitles:nil, nil];
            alert.tag = 10000;
            [alert show];
            
        }else {
            
            DLOG(@"当前为最新版本");
        }
    }
}

- (void)processData:(NSDictionary *)dataDics isCache:(BOOL) isCache {
    
    DLOG(@"dataDics is %@",dataDics);
    if ([[NSString stringWithFormat:@"%@",[dataDics objectForKey:@"error"]] isEqualToString:@"-1"]) {
        
        if(!isCache){
            // 非缓存数据，且返回的是-1 成功的数据，才更新数据源，否则不保存
            NSString *path =[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
            NSString *cachePath = [path stringByAppendingPathComponent:_cacheFileName];// 合成归档保存的完整路径
            [NSKeyedArchiver archiveRootObject:dataDics toFile:cachePath];// 数据归档，存取缓存
        }
        
        //广告滚动条.
        if (![[dataDics objectForKey:@"homeAds"] isEqual:[NSNull null]]) {
            
            NSArray *dataArr = [dataDics objectForKey:@"homeAds"];
            if ([dataArr count]!=0) {
                
                [_adArrays removeAllObjects];
                [_tempArrays removeAllObjects];
                for (NSDictionary *item in dataArr)
                {
                    AdvertiseGallery *bean = [[AdvertiseGallery alloc] init];
                    bean.title = [item objectForKey:@"title"];
                    bean.image = [CommonClass getImageUrlPath:[item objectForKey:@"image_filename"]];
                   
                    
                    bean.urlStr = [item objectForKey:@"url"];
                    bean.tag = [_tempArrays count] + 1;
                    [_tempArrays addObject:bean];
                }
                [self readData];
                _adScrollView.imageDataArray = _adArrays;

            }
        }
        
        //随取宝信息.
        if (![[dataDics objectForKey:@"bao"] isEqual:[NSNull null]]) {
            NSDictionary *sqbDict = [dataDics objectForKey:@"bao"];
            NSString *rateStr = [NSString stringWithFormat:@"%.2f%%",[sqbDict[@"apr"] floatValue]];
            _rateLabel.attributedText = [MyTools getNSMutableAttributedStringWithText:rateStr start:rateStr.length-1 end:rateStr.length textColor:RedwordColor textFont:KFontSize(13)];
            
        }
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self upload];
        });
        
        if (!isCache) {
            // 非缓存数据才显示隐藏
            [self hiddenRefreshView];
        }
        
    }else {
        if (!isCache) {
            // 非缓存数据才显示错误
            [self hiddenRefreshView];
            [SVProgressHUD showErrorWithStatus:[NSString stringWithFormat:@"%@", [dataDics objectForKey:@"msg"]]];
        }
    }
}

// 返回失败
-(void) httpResponseFailure:(NetWorkClient *)client dataTask:(NSURLSessionDataTask *)task didFailWithError:(NSError *)error
{
    [self hiddenRefreshView];
    
    [self readCache];
}

// 无可用的网络
-(void) networkError
{
    [self hiddenRefreshView];
    
    [self readCache];
    
    
}

#pragma 加载缓存数据
-(void) readCache
{
    // 刷新前先加载缓存数据
    NSString *path =[NSSearchPathForDirectoriesInDomains(NSCachesDirectory,NSUserDomainMask, YES) objectAtIndex:0];
    NSString *cachePath = [path stringByAppendingPathComponent:_cacheFileName];// 合成归档保存的完整路径
    NSDictionary *dics = [NSKeyedUnarchiver unarchiveObjectWithFile:cachePath];// 上一次缓存数据
    [self processData:dics isCache:YES];// 读取上一次成功缓存的数据
}


#pragma mark - 读取图片数据
- (void)readData
{
    NSMutableArray *itemArray = [NSMutableArray arrayWithCapacity:_tempArrays.count+2];
    //添加最后一张图 用于循环
    if (_tempArrays.count > 1)
    {
        AdvertiseGallery *bean = [_tempArrays objectAtIndex:_tempArrays.count-1];
        bean.tag = -1;
        [itemArray addObject:bean];
    }
    
    
    for (int i = 0; i < _tempArrays.count; i++)
    {
        AdvertiseGallery *bean = [_tempArrays objectAtIndex:i];
        [itemArray addObject:bean];
    }
    
    //添加第一张图 用于循环
    if (_tempArrays.count >1)
    {
        AdvertiseGallery *bean = [_tempArrays objectAtIndex:0];
        bean.tag = _tempArrays.count;
        [itemArray addObject:bean];
    }
    
    [_adArrays addObjectsFromArray:itemArray];
    
}

#pragma mark - 刷新
- (void)headerRereshing {
    [self requestData];
   
}

#pragma 隐藏刷新视图
- (void)hiddenRefreshView {
    
    if (!_scrollContent.mj_header.hidden) {
        [_scrollContent.mj_header endRefreshing];
    }
    if (!_scrollContent.mj_footer.hidden) {
        [_scrollContent.mj_footer endRefreshing];
    }
}


//字符串转字典
- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

#pragma mark - 初始化视图
- (void)initView {
    _scrollContent = [UIScrollView scrollViewWithFrame:RECTMAKE(0, 0, MSWIDTH, MSHIGHT - 64 - 49) delegate:self backgroundColor:nil superview:self.view];
    
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    _scrollContent.mj_header = [MJChiBaoZiHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRereshing)];
     [_scrollContent.mj_header beginRefreshing];
    
    _adScrollView = [[DWRollScrollView alloc] initWithFrame:CGRectMake(0, 0, MSWIDTH, MSWIDTH/2 - 20)];
    _adScrollView.backgroundColor = [UIColor whiteColor];
    _adScrollView.cornerRadius = 5.0f;
    _adScrollView.delegate = self;
//    _adScrollView.contentMode = UIViewContentModeScaleAspectFill;
    [_scrollContent addSubview:_adScrollView];
    [_scrollContent addSubview:self.publicView];
    _tenderInfoScrollView = [UIScrollView scrollViewWithFrame:RECTMAKE(0, GetMaxY(_adScrollView) + 30, MSWIDTH, GetHeight(_scrollContent)- GetMaxY(_adScrollView)) delegate:self backgroundColor:[UIColor whiteColor] superview:_scrollContent];
    _tenderInfoScrollView.contentInset = UIEdgeInsetsZero;
    [_tenderInfoScrollView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tenderInfoViewTap)]];
    
    [self loadContentView];
    
    if (GetMaxY(_tenderInfoScrollView) <= GetHeight(_scrollContent)) {
        _scrollContent.contentSize = CGSizeMake(MSWIDTH, GetHeight(_scrollContent)+1);
    }else {
        _scrollContent.contentSize = CGSizeMake(MSWIDTH, GetMaxY(_tenderInfoScrollView));
    }
    
}

- (void)loadContentView {
    
    _stausImageView = [UIImageView imageViewWithFrame:RECTMAKE(MSWIDTH - 40, KAdaptNum(20), KAdaptNum(30), KAdaptNum(30)) imageFile:@"" superview:_tenderInfoScrollView];
    _stausImageView.image = [UIImage imageNamed:@"Home_InvestStaus"];
    
    _titleLabel = [UILabel labelWithFrame:RECTMAKE(40, KAdaptNum(20), MSWIDTH - 80, KAdaptNum(30)) text:@"随取宝" textColor:KBlackColor textFont:18 fitWidth:NO superview:_tenderInfoScrollView];
    _titleLabel.textAlignment = NSTextAlignmentCenter;
    
    _rateValue = [UILabel labelWithFrame:RECTMAKE(10, GetMaxY(_titleLabel) + KAdaptNum(20), MSWIDTH - 20, KAdaptNum(20)) text:@"7日年化收益率" textColor:KGrayColor textFont:12 fitWidth:NO superview:_tenderInfoScrollView];
    _rateValue.textAlignment = NSTextAlignmentCenter;
    
    _rateLabel = [UILabel labelWithFrame:RECTMAKE(10, GetMaxY(_rateValue) + KAdaptNum(10), MSWIDTH - 20, KAdaptNum(30)) text:@"" textColor:RedwordColor textFont:36 fitWidth:NO superview:_tenderInfoScrollView];
    _rateLabel.textAlignment = NSTextAlignmentCenter;
    
    UIView *line = [UIView viewWithFrame:RECTMAKE(75, GetMaxY(_rateLabel) + KAdaptNum(10), MSWIDTH - 150, kLineHeight) backgroundColor:KlayerBorder superview:_tenderInfoScrollView];
    
    UILabel *mindLabel = [UILabel labelWithFrame:RECTMAKE(GetMinX(line), GetMaxY(line), GetWidth(line), KAdaptNum(30)) text:@"随存随取 | 便捷理财" textColor:KBlackColor textFont:13 fitWidth:NO superview:_tenderInfoScrollView];
    mindLabel.textAlignment = NSTextAlignmentCenter;
    
    UIView *line1 = [UIView viewWithFrame:RECTMAKE(GetMinX(line), GetMaxY(mindLabel), GetWidth(line), kLineHeight) backgroundColor:KlayerBorder superview:_tenderInfoScrollView];
    
    _tenderButton = [[ClickButton alloc] initWithFrame:RECTMAKE(55, GetMaxY(line1) + KAdaptNum(20), MSWIDTH - 110, KAdaptNum(44))];
    [_tenderButton setTitle:@"" forState:UIControlStateNormal];
    _tenderButton.layer.cornerRadius = GetHeight(_tenderButton)/2;
    [_tenderButton setTitle:@"立即进入" forState:UIControlStateNormal];
    [_tenderButton addTarget:self action:@selector(tenderButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [_tenderInfoScrollView addSubview:_tenderButton];
    
    //UILabel *tenderValue = [UILabel labelWithFrame:RECTMAKE(10, GetHeight(_tenderButton)/6, GetWidth(_tenderButton) - 20, GetHeight(_tenderButton)/2) text:@"立即进入" textColor:[UIColor whiteColor] textFont:15 fitWidth:NO superview:_tenderButton];
    
    //UILabel *tenderValue1 = [UILabel labelWithFrame:RECTMAKE(10, GetHeight(_tenderButton)/2, GetWidth(_tenderButton) - 20, GetHeight(_tenderButton)/2) text:@"100%本金保障" textColor:[UIColor whiteColor] textFont:10 fitWidth:NO superview:_tenderButton];
    //tenderValue.textAlignment = NSTextAlignmentCenter;
    //tenderValue1.textAlignment = NSTextAlignmentCenter;
    
    NSString *securityStr = @"信托及资管等国有金融机构产品";
    CGFloat secuWidth = [MyTools getSizeOfString:securityStr maxWidth:MSWIDTH - 20 - 15 maxHeight:20 withFontSize:10].width;
    
    UIImageView *secuImageView = [UIImageView imageViewWithFrame:RECTMAKE((MSWIDTH - secuWidth - 15)/2, GetMaxY(_tenderButton) + KAdaptNum(20), KAdaptNum(11), KAdaptNum(13)) imageFile:@"HomeSecurity" superview:_tenderInfoScrollView];
    
    [UILabel labelWithFrame:RECTMAKE(GetMaxX(secuImageView)+KAdaptNum(4), GetMinY(secuImageView), secuWidth, GetHeight(secuImageView)) text:securityStr textColor:KGrayColor textFont:10 fitWidth:NO superview:_tenderInfoScrollView];
    
    _tenderInfoScrollView.contentSize = CGSizeMake(MSWIDTH, GetMaxY(secuImageView)+10);
}


#pragma mark - Navigation
- (void)initNavigationBar
{
    self.title = NSLocalizedString(@"Tab_Home_Title", nil);
}


#pragma mark - 广告
-(PublicNoticeView *)publicView{
    if (_publicView == nil) {
        _publicView = [[PublicNoticeView alloc] init];
        _publicView.frame = RECTMAKE(0, GetMaxY(_adScrollView), MSWIDTH, 30);
        _publicView.backgroundColor = [UIColor clearColor];
        
    }
    return _publicView;
}
- (void)gotoMessage:(NSNotification *)notifi{
    
    MessageModel *model = notifi.object;
    MessageDetailViewController *detail = [[MessageDetailViewController alloc] init];
    detail.messageModel = model;
    detail.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:detail animated:YES];
   
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end


/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */
